'''
请求的处理与响应
'''
from weather.models import *
from weather.api.serializers import CityNumberSerializer, WeatherLiveSerializer
from rest_framework import status, renderers, viewsets
from rest_framework.permissions import IsAuthenticated, IsAuthenticatedOrReadOnly
from rest_framework.authtoken.views import ObtainAuthToken
from rest_framework.authtoken.models import Token
from rest_framework.response import Response
from weather.api import DynamicFieldsViewMixin
# from rest_framework.authentication import TokenAuthentication


class CityNumberApiView(viewsets.ModelViewSet):
    ''''''
    queryset = CityNumber.objects.all()
    serializer_class = CityNumberSerializer


class WeatherLiveApiView(DynamicFieldsViewMixin, viewsets.ModelViewSet):
    '''可更新，删除'''
    queryset = WeatherLive.objects.all()
    serializer_class = WeatherLiveSerializer
    # permission_classes = [IsAuthenticated]

    filterset_fields = ['wind_level', 'pm25']
    search_fields = ['temp', 'wind_level',]
    ordering_fields = ['temp', 'wind_level', 'pm25']


# # 以WeatherLive为示例
# class WeatherReadOnlyApiView(DynamicFieldsViewMixin, viewsets.ReadOnlyModelViewSet):
#     '''只读接口'''
#     queryset = WeatherLive.objects.filter(wind_level=1)
#     serializer_class = WeatherLiveSerializer
#     permission_classes = [IsAuthenticated]

#     filterset_fields = ['wind_level', 'pm25']
#     search_fields = ['temp', 'wind_level',]
#     ordering_fields = ['temp', 'wind_level', 'pm25']


class CustomAuthToken(ObtainAuthToken):
    '''
    实现token认证接口
    '''
    renderer_classes = (renderers.JSONRenderer, renderers.BrowsableAPIRenderer)

    def post(self, request, *args, **kwargs):
        serializer = self.serializer_class(data=request.data,
                                           context={'request': request})
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        token, created = Token.objects.get_or_create(user=user)
        return Response({
            'token': token.key,
            'user_id': user.pk,
            'email': user.email
        })
